from tools import *
from common.utils import find_duplicates, check_filename_format


def extract_parts_from_series(series, part_index):
    if part_index < 1 or part_index > 2:
        raise ValueError("part_index 必须在 1 到 2 之间")

    # 编译高效的正则表达式
    # pattern = re.compile(r'^([^-.]+)-([^-.]+)\.([^-.]+)$')

    # 提取函数
    def extract_part(s):
        match = re.compile(PATTERN_视频).match(s)
        if match:
            return match.group(part_index)
        return None  # 不符合格式的返回None

    # 应用提取函数并返回Series
    return series.apply(extract_part)


def check_视频_filename_format(filename_list):
    return check_filename_format(filename_list, PATTERN_视频)


def get_segment_from_视频_filename(files_name: pd.Series,
                                   part_index: int,
                                   segment_name: str,
                                   check_duplicates: bool = False):
    extracted = extract_parts_from_series(files_name, part_index)

    if check_duplicates and find_duplicates(extracted):
        exit(0)

    extracted.name = segment_name
    return extracted


def get_课设视频_提交记录(output_path=None) -> DataFrame:
    target = '视频'
    df_学生_信息 = get_学生_信息()

    files = get_视频_files_name(f"{BASE_PATH_企业级应用课设}\提交\视频")

    se_files_name = pd.Series(files, name="文件名")
    se_学号 = get_segment_from_视频_filename(se_files_name, 1, '学号', True).astype(int)
    se_姓名 = get_segment_from_视频_filename(se_files_name, 2, '姓名', True).astype(str)
    df_merged = pd.concat([se_学号, se_姓名], axis=1)
    df_merged['已提交'] = 'Y'
    df_merged = merge_student_dataframes(df_学生_信息, df_merged)

    if output_path:
        df_merged.to_excel(output_path, index=False)
        print(f"\n✅ 课设{target}提交记录统计完成! 文件已保存至: {output_path}\n")

    return df_merged


if __name__ == "__main__":
    df_学生_信息 = get_学生_信息()

    path1 = f"{BASE_PATH_企业级应用课设}\提交\视频提交_汇总.xlsx"
    df_提交记录 = get_课设视频_提交记录()
    print(df_提交记录)
